/* *****************************************************************************************************
 * Copyright 2009. Dbwebx Group
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 * *****************************************************************************************************
 */

package org.dbwebx.service.dao.impl;

import org.dbwebx.adapter.jcr.util.JcrUtils;
import org.dbwebx.domain.DbUnit;
import org.dbwebx.jcr.JcrService;
import org.dbwebx.jcr.domain.DbUnitNode;
import org.dbwebx.persistence.Bundle;
import org.dbwebx.persistence.JCRDBUnit;
import org.dbwebx.service.dao.DbUnitService;
import org.dbwebx.service.dao.impl.base.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * The JCR {@link DbUnitService} implementation.
 * 
 * @author Izzet_Mustafayev
 * 
 */
@Repository("dbUnitService")
@Transactional
public class JcrDbUnitService extends
		BaseService<DbUnit, org.dbwebx.persistence.DBUnit> implements
		DbUnitService {

	/**
	 * The {@link JcrService} reference.
	 */
	@Autowired
	private JcrService jcrService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.dbwebx.service.dao.DbUnitService#persist(org.dbwebx.domain.DbUnit)
	 */
	public DbUnit persist(final DbUnit dbunit) {
		DbUnit result = null;
		if (null != dbunit) {
			result = saveUnit(dbunit);
		}
		return result;
	}

	private DbUnit saveUnit(final DbUnit dbunit) {
		DbUnit resultUnit;
		JCRDBUnit jcrdbUnit = new JCRDBUnit();
		jcrdbUnit.setName(dbunit.getName());
		jcrdbUnit.setBundle(dozerMapper.map(dbunit.getBundle(), Bundle.class));
		jcrdbUnit = em.merge(jcrdbUnit);
		String basePath;
		basePath = JcrUtils.createBasePath(jcrdbUnit);
		DbUnitNode dbNode = jcrService.persist(basePath, jcrdbUnit.getName(),
				dbunit.getData());
		jcrdbUnit.setPath(dbNode.getPath());
		resultUnit = dozerMapper.map(em.merge(jcrdbUnit), DbUnit.class);
		resultUnit.setData(dbunit.getData());
		resultUnit.setVersion(dbNode.getVersion());
		return resultUnit;
	}

}
